package com.xd.common.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Slf4j
//@WebFilter(urlPatterns = "/", filterName = "SqlInjectionFilter")
//@Configuration
public class SqlInjectionFilter implements Filter {

    //放行URL
    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/sys-user/register",
                    "/user/login",
                    "/sys-user/forgetPassword",
                    "/file/upload",
                    "/file/uploadAuthentication",
                    "/file/uploadVoucher",
                    "/file/uploadAdvert",
                    "/core/sys-permission")));

    private static final String SQL_REG_EXP = ".*(\\b(select|insert|into|update|delete|from|where|trancate" +
            "|drop|execute|grant|use|union)\\b).*";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        CustomRequestWrapper requestWrapper = new CustomRequestWrapper(request);
        Map<String, Object> parameterMap = new HashMap<>();
        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
        boolean allowedPath = ALLOWED_PATHS.contains(path);
        if (!allowedPath) {
            parameterMap = getParameterMap(parameterMap, request, requestWrapper);
            // 正则校验是否有SQL关键字
            for (Object obj : parameterMap.entrySet()) {
                Map.Entry entry = (Map.Entry) obj;
                Object value = entry.getValue();
                if (value != null) {
                    boolean isValid = isSqlInject(value.toString(), servletResponse);
                    if (!isValid) {
                        return;
                    }
                }
            }
        }
        filterChain.doFilter(requestWrapper, servletResponse);
    }


    private Map<String, Object> getParameterMap(Map<String, Object> paramMap, HttpServletRequest request, CustomRequestWrapper requestWrapper) {
        // 1.POST请求获取参数
        if ("POST".equals(request.getMethod().toUpperCase())) {
            String body = requestWrapper.getBody();
            if (StringUtils.isNotEmpty(body)) {
                boolean jsonType = getJSONType(body);
                if (jsonType == true) {
                    if (body.startsWith("[") && body.endsWith("]")) {
                        JSONArray split = JSONObject.parseArray(body);
                        Map<String, Object> map = new HashMap<>();
                        for (Object o : split) {
                            map.put(o.toString(), o);
                        }
                        paramMap = map;
                    } else {
                        paramMap = JSONObject.parseObject(body, HashMap.class);
                    }
                } else {
                    String[] split = body.split("&");
                    for (int i = 0; i < split.length; i++) {
                        String[] split1;
                        split1 = split[i].split("=");
                        paramMap.put(split1[0], split1[1]);
                        split1 = null;
                    }
                }
            } else {
                Map<String, String[]> parameterMap = requestWrapper.getParameterMap();
                if (parameterMap != null && parameterMap.size() > 0) {
                    Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
                    for (Map.Entry<String, String[]> next : entries) {
                        paramMap.put(next.getKey(), next.getValue()[0]);
                    }
                }
            }
        } else {
            Map<String, String[]> parameterMap = requestWrapper.getParameterMap();
            //普通的GET请求
            if (parameterMap != null && parameterMap.size() > 0) {
                Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
                for (Map.Entry<String, String[]> next : entries) {
                    paramMap.put(next.getKey(), next.getValue()[0]);
                }
            }
            /*else {
                //GET请求,参数在URL路径型式,比如server/{var1}/{var2}
                String afterDecodeUrl = null;
                try {
                    //编码过URL需解码解码还原字符
                    afterDecodeUrl = URLDecoder.decode(request.getRequestURI(), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                paramMap.put("pathVar", afterDecodeUrl);
            }*/
        }
        return paramMap;
    }

    private boolean isSqlInject(String value, ServletResponse servletResponse) throws IOException {
        if (null != value && value.toLowerCase().matches(SQL_REG_EXP)) {
            log.info("入参中有非法字符: " + value);
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            Map<String, String> responseMap = new HashMap<>();
            // 匹配到非法字符,立即返回
            responseMap.put("code", "999");
            responseMap.put("message", "入参中有非法字符");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpStatus.OK.value());
            response.getWriter().write(JSON.toJSONString(responseMap));
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }
        return true;
    }

    private boolean getJSONType(String str) {
        boolean result = false;
        if (StringUtils.isNotBlank(str)) {
            str = str.trim();
            if (str.startsWith("{") && str.endsWith("}")) {
                result = true;
            } else if (str.startsWith("[") && str.endsWith("]")) {
                result = true;
            }
        }
        return result;
    }

    @Override
    public void destroy() {

    }
}